package tcp.filetransfer;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.ExecutorService;

import constants.NetworkConstants;

public class DownloadManager extends Thread {
	private FileTransferManager manager ;
	private int portNumber;
	
	DownloadManager(FileTransferManager manager){
		this.manager = manager;
		this.portNumber = NetworkConstants.DEFAULT_FD_PORT;
		this.start();
	}
	public DownloadManager(FileTransferManager manager, int portNumber) {
		this.manager = manager; 
		this.portNumber = portNumber;
		this.start();
	}
	private void setupListeningForDownloadRequests(){
		ServerSocket serverSocket = null;
        boolean listening = true;
        try {
			serverSocket = new ServerSocket(this.portNumber);

	        while (listening){
	        	ExecutorService pool = this.manager.getThreadPool() ;
	        	pool.execute(new DownloadHandler(serverSocket.accept(),this.manager.getFileHandler()));
	        }
	        serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Override
	public void run() {
		this.setupListeningForDownloadRequests();
	}
	
}
